package com.guyaogg.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guyaogg.common.utils.PageUtils;
import com.guyaogg.common.utils.Query;
import com.guyaogg.common.utils.R;
import com.guyaogg.common.utils.StringUtils;
import com.guyaogg.gulimall.product.dao.SkuInfoDao;
import com.guyaogg.gulimall.product.entity.SkuImagesEntity;
import com.guyaogg.gulimall.product.entity.SkuInfoEntity;
import com.guyaogg.gulimall.product.entity.SpuInfoDescEntity;
import com.guyaogg.gulimall.product.feign.SeckillFeignService;
import com.guyaogg.gulimall.product.service.*;
import com.guyaogg.gulimall.product.vo.SeckillInfoVO;
import com.guyaogg.gulimall.product.vo.SkuItemVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    private final SkuImagesService skuImagesService;
    private final SpuInfoDescService spuInfoDescService;
    private final AttrGroupService attrGroupService;
    private final SkuSaleAttrValueService skuSaleAttrValueService;
    private final ThreadPoolExecutor threadPoolExecutor;
    private final SeckillFeignService seckillFeignService;

    public SkuInfoServiceImpl(SkuImagesService skuImagesService, SpuInfoDescService spuInfoDescService, AttrGroupService attrGroupService, SkuSaleAttrValueService skuSaleAttrValueService, ThreadPoolExecutor threadPoolExecutor, SeckillFeignService seckillFeignService) {
        this.skuImagesService = skuImagesService;
        this.spuInfoDescService = spuInfoDescService;
        this.attrGroupService = attrGroupService;
        this.skuSaleAttrValueService = skuSaleAttrValueService;
        this.threadPoolExecutor = threadPoolExecutor;
        this.seckillFeignService = seckillFeignService;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    /**
     * {
     * page: 1,//当前页码
     * limit: 10,//每页记录数
     * sidx: 'id',//排序字段
     * order: 'asc/desc',//排序方式
     * key: '华为',//检索关键字
     * catelogId: 0,
     * brandId: 0,
     * min: 0,
     * max: 0
     * }
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            String trimKey = key.trim();
            wrapper.and(w -> w.eq("sku_id", trimKey).or().like("sku_name", trimKey));
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && Integer.parseInt(brandId) > 0) {
            wrapper.eq("brand_id", brandId);

        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && Integer.parseInt(catelogId) > 0) {
            wrapper.eq("catalog_id", catelogId);

        }


        String min = (String) params.get("min");

        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            BigDecimal maxBigDecimal = new BigDecimal(max);
            if (maxBigDecimal.compareTo(new BigDecimal(0)) > 0) {
                wrapper.le("price", max);
            }
        }

        log.debug("key:{},brandId:{},catelogId{},min:{},max:{}", key, brandId, catelogId, min, max);
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySkuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id", spuId);
        return this.list(wrapper);
    }

    /**
     * 异步编排实现查询 sku 信息
     *
     * @param skuId
     * @return
     */
    @Cacheable(value = {"skuinfo"}, key = "'item'+#root.args[0]", sync = true)
    @Override
    public SkuItemVO item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVO skuItem = new SkuItemVO();

        // 1.sku 基本信息获取  pms_sku_info

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {

            SkuInfoEntity info = getById(skuId);
            skuItem.setInfo(info);
            return info;
        }, threadPoolExecutor);

        // TODO 3.获取 sku 的销售属性组合

        CompletableFuture<Void> saleAttrsFuture = infoFuture.thenAcceptAsync(res -> {
            List<SkuItemVO.ItemSaleAttrsVO> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItem.setSaleAttrs(saleAttrs);
        }, threadPoolExecutor);

        // 4.获取 spu 的介绍 pms_spu_info_desc

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(res -> {
            SpuInfoDescEntity desc = spuInfoDescService.getById(res.getSpuId());
            skuItem.setDesc(desc);
        }, threadPoolExecutor);

        // TODO 5.获取 spu 的规格参数信息

        CompletableFuture<Void> baseAttrsFuture = infoFuture.thenAcceptAsync(res -> {
            List<SkuItemVO.SpuItemBaseAttrVO> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItem.setGroupAttrs(groupAttrs);
        }, threadPoolExecutor);

        // 2.sku 的图片信息  pms_sku_images

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            skuItem.setImages(images);
        }, threadPoolExecutor);

        // 6.查询当前 sku 是否参与秒杀优惠
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R seckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            if (seckillInfo.getCode() == 0) {
                SeckillInfoVO seckillInfoVO = seckillInfo.getData(new TypeReference<SeckillInfoVO>() {
                });
                skuItem.setSeckillInfoVO(seckillInfoVO);
            }
        }, threadPoolExecutor);



        // 等待所有任务都完成,,infoFuture 可省
        CompletableFuture.allOf(seckillFuture,infoFuture, saleAttrsFuture, descFuture, baseAttrsFuture, imagesFuture).get();

        return skuItem;
    }

}